package ferran.tomas.ta;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Stack;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import ferran.tomas.dominio.Checkpoint;
import ferran.tomas.dominio.Itinerario;
import ferran.tomas.dominio.User;

/**
 * @author Tomas
 * 
 */
public class MapaActivity extends MapActivity {
	private MapController mapController;
	private MapView map = null;
	public GeoPoint miPosicion;
	private ArrayList<GeoPoint> destinaciones;
	private ArrayList<Integer> marcadores;


	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.maps);
		
		Itinerario it = null;
		try {
			it = ControladorItinerario.getInstancia().getItinerario(User.getInstancia().getNombre());
		} catch (NoItinerariosException ex) {
			Toast.makeText(getApplicationContext(), "Usted no tiene un itinerario asignado", Toast.LENGTH_LONG).show();
		}
		catch (Exception e) {
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		
		Log.d("ONCREATEMAPACTIVITY", it.toString());
		
		marcadores = new ArrayList<Integer>(4);
		destinaciones = new ArrayList<GeoPoint>(4);
		
		/* descomentar si vamos a usar un movil 
		 * 
		marcadores = new Stack<Integer>();
		destinaciones = new Stack<GeoPoint>();
		ArrayList<Checkpoint> cp = it.getCps();
		
		for (Checkpoint checkpoint : cp) {
			String pos = checkpoint.getPosicion();
			List<Address> l = null;
			Geocoder g = new Geocoder(this, Locale.getDefault());
			try {
				l = g.getFromLocationName(pos, 1);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(l != null) {
				int latitud =  (int) ((int) l.get(0).getLatitude() * 1E6);
				int longitud =  (int) ((int) l.get(0).getLongitude() * 1E6);
				
				destinaciones.add(new GeoPoint(latitud, longitud));
				marcadores.add(R.drawable.a1);
			}
		}
		*/
		destinaciones.add(new GeoPoint(51511734,-328403));
		marcadores.add(R.drawable.a5);
		//Paris France
		destinaciones.add(new GeoPoint(48858165,2352791));
		marcadores.add(R.drawable.a1);
		//Bremen Germany
		destinaciones.add(new GeoPoint(53094024,8789063));
		marcadores.add(R.drawable.a2);
		//Tuscany Italy
		destinaciones.add(new GeoPoint(43834527,11206055));
		marcadores.add(R.drawable.a3);
		
		/*
		 * List<Address> l = null;
			Geocoder g = new Geocoder(getApplicationContext());
			try {
				l = g.getFromLocationName("Paris, France", 1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			l.get(0).getLatitude();
			l.get(0).getLongitude();
		 */
		
		
		

		map = (MapView) findViewById(R.id.map);
		map.setBuiltInZoomControls(true);

		mapController = map.getController();
		mapController.setZoom(7);
		
		int minLatitude = Integer.MAX_VALUE;
		int maxLatitude = Integer.MIN_VALUE;
		int minLongitude = Integer.MAX_VALUE;
		int maxLongitude = Integer.MIN_VALUE;
		int i = 0;
		// Find the boundaries of the item set
		for (GeoPoint item : destinaciones) { //item Contain list of Geopints
			
			map.getOverlays().add(new LocationWinOverLay(item, marcadores.get(i), i+1));
			++i;
	
			int lati = item.getLatitudeE6();
			int lon = item.getLongitudeE6();
			
			maxLatitude = Math.max(lati, maxLatitude);
			minLatitude = Math.min(lati, minLatitude);
			maxLongitude = Math.max(lon, maxLongitude);
			minLongitude = Math.min(lon, minLongitude);
		 }
		mapController.zoomToSpan(Math.abs(maxLatitude - minLatitude), Math.abs(maxLongitude - minLongitude));
		mapController.animateTo(new GeoPoint( 
				(maxLatitude + minLatitude)/2, 
				(maxLongitude + minLongitude)/2 )); 
		

		/* Use the LocationManager class to obtain GPS locations */
		LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		/* minDistante = 10m, minTime = 10s for notifications */
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000,
				10, new GeoUpdateHandler());

		MyLocationOverlay me = new MyLocationOverlay();
		map.getOverlays().add(me);
	}
	
	// option menu
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_S) {
			map.setSatellite(!map.isSatellite());
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_Z) {
			map.displayZoomControls(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.google.android.maps.MapActivity#isRouteDisplayed()
	 */
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public class GeoUpdateHandler implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			Log.d("updateGEO", "Updated geo "+Integer.toString(lat)+" "+Integer.toString(lng));

			miPosicion = new GeoPoint(lat, lng);
			
			//mapController.animateTo(miPosicion); // mapController.setCenter(point);
		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), provider + " Disabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), provider + " Enabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	public class MyLocationOverlay extends Overlay {

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			super.draw(canvas, mapView, shadow);

			if (miPosicion != null) {
				Paint paint = new Paint();
				Point myScreenCoords = new Point();
				mapView.getProjection().toPixels(miPosicion, myScreenCoords);
				paint.setStrokeWidth(1);
				paint.setARGB(255, 0, 0, 0);
				paint.setStyle(Paint.Style.STROKE);
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.marker);
				canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y,
						paint);
				canvas.drawText(getString(R.string.mylocation),
						myScreenCoords.x, myScreenCoords.y, paint);
				return true;
			}

			return false;
		}
	}

	public class LocationWinOverLay extends Overlay {
		private GeoPoint loc;
		private int marker;
		private String palabra;

		public LocationWinOverLay(GeoPoint Loc, int marker, int i) {
			this.loc = Loc;
			this.marker = marker;
			this.palabra = Integer.toString(i);
		}

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,	long when) {
			super.draw(canvas, mapView, shadow);

			Paint paint = new Paint();
			Point myScreenCoords = new Point();
			mapView.getProjection().toPixels(loc, myScreenCoords);
			paint.setStrokeWidth(1);
			paint.setARGB(255, 255, 0, 0);
			paint.setStyle(Paint.Style.STROKE);
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), this.marker);
			canvas.drawBitmap(bmp, myScreenCoords.x-10, myScreenCoords.y-15, paint);
			canvas.drawText(this.palabra, myScreenCoords.x, myScreenCoords.y, paint);
			return true;
		}
	}

}
